import {
  MessageBody,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
  ConnectedSocket
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getRepository } from 'typeorm';
import { createWriteStream } from 'fs';
import { join } from 'path';
import { User } from '../../entities';
import { UserMap } from '../friend/entity/friend.entity';

@WebSocketGateway()
export class ChatGateway {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(UserMap)
    private friendRepository: Repository<UserMap>,
  ) {}

  @WebSocketServer()
  server: Server;

  /** socket连接钩子 */
  async handleConnection(client: Socket): Promise<string> {
    const userRoom = client.handshake.query.uid;
    // 用户独有消息房间 根据userId
    if(userRoom) {
      client.join(userRoom);
    }
    return '连接成功';
  }

  /** socket断连钩子 */
  async handleDisconnect(): Promise<any> {
    return '断开连接';
  }

  /** 加入私聊的socket连接 */
  @SubscribeMessage('joinFriendSocket')
  async joinFriend(@ConnectedSocket() client: Socket, @MessageBody() data: UserMap): Promise<any> {
    if(data.uid && data.friendId) {
      const relation = await this.friendRepository.findOne({uid: data.uid, friendId: data.friendId});
      const roomId = data.uid + data.friendId;
      if(relation) {
        client.join(roomId);
        this.server.to(data.uid).emit('joinFriendSocket', {
          message: '加入私聊连接成功',
          value: {
            roomId: roomId,
            relation: relation,
          }
        });
      }
    }
  }


}